﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace TorrentProxy
{
	public partial class LogDialog : Form
	{
		public Proxy Proxy { get; set; }
		
		public LogDialog()
		{
			InitializeComponent();
		}

		private void LogDialog_Load(object sender, EventArgs e)
		{
			LoadLog();
		}

		private void LoadLog()
		{
			listView.SuspendLayout();
			listView.Items.Clear();
			foreach (LogItem logItem in Proxy.Log)
			{
				ListViewItem item =
					new ListViewItem(new[]
					                 	{
					                 		logItem.Status.ToString(), logItem.Tracker, FormatBytes(logItem.Downloaded),
					                 		FormatBytes(logItem.Uploaded)
					                 	}) { Tag = logItem };
				listView.Items.Add(item);
			}
			listView.ResumeLayout();
		}

		private static string FormatBytes(long bytes)
		{
			const int scale = 1024;
			string[] orders = new[] { "GB", "MB", "KB", "Bytes" };
			long max = (long)Math.Pow(scale, orders.Length - 1);

			foreach (string order in orders)
			{
				if (bytes > max)
					return string.Format("{0:##.##} {1}", decimal.Divide(bytes, max), order);

				max /= scale;
			}
			return "0 Bytes";
		}

		private void btnClose_Click(object sender, EventArgs e)
		{
			Close();
		}

		private void btnRefresh_Click(object sender, EventArgs e)
		{
			LoadLog();
		}

		private void timer_Tick(object sender, EventArgs e)
		{
			LoadLog();
		}
	}
}
